package view;

import Dao.User;
import Dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class loginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        // 1. 先从请求中读取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || "".equals(username) || password == null || "".equals(password)){
            resp.getWriter().write("    <script>alert(\"用户名密码错误!\")</script>\n");
            return;
        }
        // 2. 从数据库里根据用户名查询密码
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if (user == null){
            resp.getWriter().write("<script>alert(\"用户名密码错误!\")</script>\n");
            return;
        }
        // 3. 吧数据库里查出的密码和输入密码比较
        if(!user.getPassword().equals(password)){
            resp.getWriter().write("<script>alert(\"用户名密码错误!\")</script>\n");
            return;
        }
        // 4. 如果登录成功,就吧user对象存到 HttpSession 中
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        // 5. 登录成功之后 重定向到 index.html中
        resp.sendRedirect("index.html");
    }
}
